﻿using System;
using System.Collections.Generic;

using System.IO;
using System.Xml;

namespace State_Machine
{
    /// <summary>
    /// File Loader for the State Machine
    /// Loading from a XML file
    /// </summary>
    static public class MachineLoader
    {
        static public Machine Loader(string assetName)
        {
            Machine m = new Machine();

            StreamReader reader = new StreamReader(assetName);

            XmlDocument machineState = new XmlDocument();
            machineState.LoadXml(reader.ReadToEnd());

            reader.Close();

            // Read the root node
            XmlNode root = machineState.SelectSingleNode("Machine");

            // Add the states
            foreach (XmlNode it_states in root.SelectNodes("State"))
            {
                parseState(ref m, it_states);
            }

            // Add the transitions
            foreach (XmlNode it_states in root.SelectNodes("State"))
            {
                parseTransition(ref m, it_states);
            }

            return m;
        }

        /// <summary>
        /// Load the states
        /// </summary>
        /// <param name="m">The machine to update</param>
        /// <param name="stateNode">the node to parse</param>
        static private void parseState(ref Machine m, XmlNode stateNode)
        {
            string stateName = stateNode.Attributes["Name"].InnerText.Trim();
            m.addState(stateName);
        }

        /// <summary>
        /// Load the transition
        /// </summary>
        /// <param name="m">The machine to update</param>
        /// <param name="stateNode">the node to parse</param>
        static private void parseTransition(ref Machine m, XmlNode stateNode)
        {
            // Read the name of the initial node
            string initStateName = stateNode.Attributes["Name"].InnerText.Trim();
            foreach (XmlNode it_transitions in stateNode.SelectNodes("Transition"))
            {
                // Read the transition information
                string transitionName = it_transitions.Attributes["Name"].InnerText.Trim();
                string finalStateName = it_transitions.Attributes["Dest"].InnerText.Trim();

                m.addTransition(initStateName, transitionName, finalStateName);
            }
        }
    }
}
